<?php

namespace App\Helpers;

class ErrorCodeHelper
{
    private $errors = array(
        //参数验证错误码
        "VALIDATE_ERROR" => array("code" => 10001, "msg" => "%s"),
        //上传错误码
        "UPLOAD_ERROR" => array("code" => 10002, "msg" => "%s"),
        "UNAUTHORIZED" => array("code" => 10003, "msg" => "权限不足"),

        "TOKEN_INVALID" => array("code" => 40001, "msg" => "token无效"),
        "TOKEN_OVERDUE" => array("code" => 40002, "msg" => "token过期"),
        "TOKEN_ERROR" => array("code" => 40003, "msg" => "token出错"),

        "SOCIALITE_PROVIDER_NOT_FOUND" => array("code" => 40004, "msg" => "未接入此第三方帐号类型"),
        "ENTITY_NOT_FOUND" => array("code" => 40005, "msg" => "未找到实体"),
        "TOO_MANY_ATTEMPTS" => array("code" => 40029, "msg" => "Too Many Attempts"),
    );

    /**
     * 获取错误码
     *
     * @param [string] $key
     * @return integer
     */
    public function getCode($key)
    {
        if (!is_string($key)) {
            throw new \InvalidArgumentException("Argument must be string.");
        }

        if (array_key_exists($key, $this->errors)) {
            $value = $this->errors[$key];
            return $value["code"];
        } else {
            throw new \Exception("key not exist.");
        }
    }

    /**
     * 获取错误描述
     *
     * @param [string] $key
     * @return string
     */
    public function getMessage($key)
    {
        if (!is_string($key)) {
            throw new \InvalidArgumentException("Argument must be string.");
        }

        if (array_key_exists($key, $this->errors)) {
            $value = $this->errors[$key];
            return $value["msg"];
        } else {
            throw new \Exception("key not exist.");
        }
    }

    /**
     * 获取错误码
     *
     * @param [string] $key
     * @return array
     */
    public function get($key)
    {
        if (!is_string($key)) {
            throw new \InvalidArgumentException("Argument must be string.");
        }

        if (array_key_exists($key, $this->errors)) {
            return $this->errors[$key];
        } else {
            throw new \Exception("key not exist.");
        }
    }

    /**
     * 替换错误码提示信息
     *
     * @param [string] $key
     * @param [array] $contents
     * @return array
     */
    public function replace($key, $contents)
    {
        if (!is_string($key)) {
            throw new \InvalidArgumentException("Argument must be string.");
        }

        if (array_key_exists($key, $this->errors)) {
            $value = $this->errors[$key];

            $data = array(
                "code" => $value["code"],
                "msg" => sprintf($value["msg"], $contents),
            );

            return $data;

        } else {
            throw new \Exception("key not exist.");
        }
    }

}
